package base.thread_demo.demo11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock..tryLock()的使用
 */
public class ReentrantLockDemo02 {
    private static final Logger log = LoggerFactory.getLogger(ReentrantLockDemo02.class);

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(()->{
            try {
                // 尝试获取锁，可以指定尝试等待时间，避免死锁.没有时间就表示当前获取锁失败就结束线程任务
                if(!lock.tryLock(2, TimeUnit.SECONDS)){// 1
                    log.info("{} 获取锁失败,不会进入阻塞队列等待,而是直接return",Thread.currentThread().getName());
                    return ;
                }
            } catch (InterruptedException e) {// 2
                log.info("{} 在获取锁的等待过程中被打断", Thread.currentThread().getName());
                return ;
            }
            try {
                log.info("{} 执行线程任务...", Thread.currentThread().getName());
            }finally {// 3
                lock.unlock();
            }
        },"t1");

        log.info("{} 在 t1 启动前获得了锁...", Thread.currentThread().getName());
        lock.lock();
        t1.start();

        //尝试将 main线程 修改成休眠3s,t1线程就不再等待拿锁
        Thread.sleep(1000);
        log.info("{} 释放锁", Thread.currentThread().getName());
        lock.unlock();
    }


}
